<template>
  <div class="menu">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>商品列表</span>
        <el-button type="success" icon="el-icon-plus" class="addBtn" @click="addMenu">新增</el-button>
      </div>

      <!--      搜索-->
      <div class="nav">
        <el-input placeholder="请输入商品名称" v-model="keyWord" class="input-with-select" clearable>
          <el-select slot="prepend" placeholder="请选择" v-model="typeId" @change="getList('select')">
            <el-option label="请选择" value=""></el-option>
            <el-option :label="item.title" :value="item._id" v-for="item in menuTypeList" :key="item._id"></el-option>
          </el-select>
          <el-button slot="append" icon="el-icon-search" @click="getList"></el-button>
        </el-input>
      </div>

      <!--      列表-->
      <el-table :data="menuList" style="width: 100%">
        <el-table-column prop="num" label="商品图" width="200" align="left">
          <template slot-scope="scope">
            <img :src="BASE_URL + scope.row.thumb" alt="加载失败" class="menuImg">
          </template>
        </el-table-column>
        <el-table-column prop="title" label="商品名称" align="left" class-name="title"/>
        <el-table-column prop="price" label="单价" width="120" align="center"/>
        <el-table-column prop="parentName" label="所属分类" width="120" align="center"/>
        <el-table-column label="推荐" width="100" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.recommend" active-color="#13ce66"
                       @change="setRecommend(scope.row)"></el-switch>
          </template>
        </el-table-column>

        <el-table-column prop="details" label="详情" width="300" show-overflow-tooltip align="left"/>
        <el-table-column fixed="right" label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button type="success" icon="el-icon-edit" size="mini" @click="editMenu(scope.row)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeMenu(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--      分页-->
      <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pageNum"
              :page-sizes="[5, 10, 15, 20]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
      </el-pagination>

      <!--      弹出框-->
      <el-dialog :title="title" :visible.sync="dialogTableVisible" width="500px" @close="cancel">
        <el-form ref="form" :rules="rules" :model="form" label-width="80px">
          <el-form-item label="商品名称" prop="title">
            <el-input v-model="form.title"/>
          </el-form-item>
          <el-form-item label="单价" prop="price">
            <el-input v-model="form.price"/>
          </el-form-item>
          <el-form-item label="所属分类" prop="parentId">
            <el-select v-model="form.parentId" placeholder="请选择">
              <el-option :label="item.title" :value="item._id" v-for="item in menuTypeList" :key="item._id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="商品图">
            <el-upload
                    v-model="form.thumb"
                    class="upload-demo"
                    action=""
                    :http-request="uploadFile"
                    :file-list="fileList"
                    list-type="picture">
              <el-button size="mini" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="详情">
            <el-input type="textarea" v-model="form.details"/>
          </el-form-item>
        </el-form>

        <div slot="footer">
          <el-button @click="cancel" type="danger">取 消</el-button>
          <el-button type="success" @click="submit">确 定</el-button>
        </div>
      </el-dialog>

    </el-card>
  </div>
</template>

<script>
  import {
    getMenu,
    deleteMenu,
    getMenuType,
    uploadFile,
    addMenu,
    editMenu,
    getMenuDetails,
  } from '../../api/api'
  import {BASE_URL} from "../../settings"

  export default {
    name: "Menu",
    data() {
      return {
        BASE_URL,
        keyWord: '',  //关键词
        menuList: [],  //菜单列表
        pageNum: 1,  //当前页数
        pageSize: 5,  //显示数量
        total: 10,//总条数
        dialogTableVisible: false,  //弹出框
        title: '',  //弹框标题
        form: {},  //表单
        fileList: [],  //文件列表
        typeId: '',  //分类
        menuTypeList: [],  //菜单分类列表
        rules: {
          title: [{required: true, message: '请输入商品名', trigger: 'blur'}],
          price: [{required: true, message: '请输入单价', trigger: 'blur'}],
          parentId: [{required: true, message: '请选择所属分类', trigger: 'blur'}],
          // thumb: [{ required: true, message: '请选择所属分类', trigger: 'blur' }],
        },  //表单验证
      }
    },
    methods: {
      //推荐
      async setRecommend(row) {
        const res = await editMenu(row)
        this.$message.success(res.msg)
        this.getList()
      },
      //获取菜单分类
      async getMenuType() {
        const res = await getMenuType()
        this.menuTypeList = res.data
        console.log(this.menuTypeList)
      },
      //获取菜单列表
      async getList(type) {
        if (type) this.pageNum = 1
        const res = await getMenu({
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          typeId: this.typeId,
          keyWord: this.keyWord
        })
        this.menuList = res.data.list
        this.total = res.data.total
      },
      //条数改变
      handleSizeChange(pageSize) {
        this.pageSize = pageSize
        this.getList()
      },
      //页数改变
      handleCurrentChange(pageNum) {
        this.pageNum = pageNum
        this.getList()
      },
      //删除商品
      removeMenu(row) {
        this.$confirm('确定删除商品么?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const res = await deleteMenu({id: row._id})
          this.$message.success(res.msg)
          this.getList()
        }).catch(() => this.$message.info('取消删除'))
      },
      //添加菜单
      addMenu() {
        this.title = '添加商品'
        this.dialogTableVisible = true
      },
      //修改菜单
      async editMenu(row) {
        this.title = '修改商品'
        const res = await getMenuDetails({id: row._id})
        this.form = res.data
        if (res.data.thumb) this.fileList.push({url: BASE_URL + res.data.thumb})
        this.dialogTableVisible = true
      },
      //文件上传
      async uploadFile(options) {
        let data = new FormData()
        data.append('file', options.file)
        const res = await uploadFile(data)
        this.$message.success(res.msg)
        this.form.thumb = res.data.url
        console.log(options.file)
      },
      //提交表单
      submit() {
        this.$refs.form.validate(async valid => {
          if (valid) {
            let res
            if (this.form._id) res = await editMenu(this.form)
            else res = await addMenu(this.form)
            this.$message.success(res.msg)
            this.dialogTableVisible = false
            this.reset()
            this.getList()
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      //取消表单
      cancel() {
        this.reset()
        this.fileList = []
        this.dialogTableVisible = false
      },
      //重置表单
      reset() {
        this.form = {}
        this.$refs.form.resetFields()
        this.fileList = []
      }
    },
    created() {
      this.getList()
      this.getMenuType()
    }
  }
</script>

<style scoped lang="scss">
  .menuImg {
    object-fit: cover;
    max-height: 50px;
  }

  img {
    width: 50%;
  }

  .el-select {
    width: 100px;
  }

  .nav {
    .el-input {
      width: 300px;
    }
  }
</style>
